package com.quectel.core.module.parking.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.core.parking.ParkingChargingConstants;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.parking.dao.ParkingChargingDao;
import com.quectel.core.module.parking.dto.ParkingChargingDto;
import com.quectel.core.module.parking.dto.ParkingChargingSharingTimeDto;
import com.quectel.core.module.parking.entity.ParkingChargingEntity;
import com.quectel.core.module.parking.service.ParkingChargingService;
import com.quectel.core.module.parking.service.ParkingChargingSharingTimeService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
/**
 *
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/05/11 10:26
 */
@DubboService
public class ParkingChargingServiceImpl implements ParkingChargingService{

    private static final Logger LOGGER = LoggerFactory.getLogger(ParkingChargingServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARKING_CHARGING_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARKING_CHARGING_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<ParkingChargingDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARKING_CHARGING_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private ParkingChargingDao parkingChargingDao;
    @Autowired
    private ParkingChargingSharingTimeService parkingChargingSharingTimeService;
    @Autowired
    private VillageService villageService;


    @Override
    public ParkingChargingDto selectOne(Long villageId, Byte carType) {
        ParkingChargingEntity parkingChargingEntity = parkingChargingDao.selectOne(new LambdaQueryWrapper<ParkingChargingEntity>()
                .eq(ParkingChargingEntity::getVillageId, villageId)
                .eq(ParkingChargingEntity::getCarType, carType)
                .last(SqlConstants.MYSQL_LIMIT_ONE));
        ParkingChargingDto parkingChargingDto = CopyUtils.copyObj(parkingChargingEntity, ParkingChargingDto.class);
        return paddingField(parkingChargingDto);
    }

    @Override
    public ParkingChargingDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARKING_CHARGING_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public ParkingChargingDto selectById(Long id){
            ParkingChargingEntity entity = parkingChargingDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,ParkingChargingDto.class));
    }

    @Override
    public List<ParkingChargingDto> queryList(Map<String,Object> params){
        List<ParkingChargingEntity> list = parkingChargingDao.queryList(params);
        List<ParkingChargingDto> result =  CopyUtils.copyList(list,ParkingChargingDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private ParkingChargingDto paddingField(ParkingChargingDto dto){
        if (dto != null){
            dto.setVillage(villageService.selectCacheById(dto.getVillageId()));
            dto.setSharingTimeList(parkingChargingSharingTimeService.selectByChargingId(dto.getId()));
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return parkingChargingDao.queryTotal(params);
    }

    @Override
    @Transactional
    public Long save(ParkingChargingDto dto){
        ParkingChargingEntity entity = CopyUtils.copyObj(dto,ParkingChargingEntity.class);
        entity.setId(Snowflake.nextId());
        parkingChargingDao.insert(entity);

        if (ParkingChargingConstants.ChargingTypeEnum.TIME_SHARING.getChargingType().equals(dto.getType())) {
            // 分时计算规则保存
            List<ParkingChargingSharingTimeDto> sharingTimeList = dto.getSharingTimeList();
            sharingTimeList.forEach(o -> o.setParkingChargingId(entity.getId()));
            parkingChargingSharingTimeService.saveBatch(sharingTimeList);
        }
        return entity.getId();
    }

    @Override
    @Transactional
    public void updateById(ParkingChargingDto dto){
        ParkingChargingEntity entity = CopyUtils.copyObj(dto,ParkingChargingEntity.class);

        parkingChargingDao.updateById(entity);

        if (ParkingChargingConstants.ChargingTypeEnum.TIME_SHARING.getChargingType().equals(dto.getType())){
            Long[] itemIds = parkingChargingSharingTimeService.selectByChargingId(dto.getId())
                    .parallelStream()
                    .map(ParkingChargingSharingTimeDto::getId)
                    .toArray(Long[]::new);
            parkingChargingSharingTimeService.deleteBatch(itemIds);

            List<ParkingChargingSharingTimeDto> sharingTimeList = dto.getSharingTimeList();
            sharingTimeList.forEach(o -> o.setParkingChargingId(entity.getId()));
            parkingChargingSharingTimeService.saveBatch(sharingTimeList);
        }
        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(ParkingChargingDto dto) {
       ParkingChargingEntity entity = CopyUtils.copyObj(dto,ParkingChargingEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, parkingChargingDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        parkingChargingDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            ParkingChargingDto parkingChargingDto = selectCacheById(id);
            if (parkingChargingDto != null
                    && ParkingChargingConstants.ChargingTypeEnum.TIME_SHARING.getChargingType().equals(parkingChargingDto.getType())) {
                Long[] itemIds = parkingChargingSharingTimeService.selectByChargingId(parkingChargingDto.getId())
                        .parallelStream()
                        .map(ParkingChargingSharingTimeDto::getId)
                        .toArray(Long[]::new);
                parkingChargingSharingTimeService.deleteBatch(itemIds);
            }
            deleteById(id);
        }
    }
}
